﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace AutoUpdater
{
    public partial class UpdateForm : Form
    {
        private UpdateManager updateManager;
        private BackgroundWorker backgroundWorker;

        public bool UpdateSuccessful { get; private set; }

        public UpdateForm(UpdateManager manager)
        {
            InitializeComponent();
            updateManager = manager;
            UpdateSuccessful = false;
            SetupBackgroundWorker();
            StartUpdate();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 窗体设置
            this.Text = "正在更新";
            this.Size = new System.Drawing.Size(450, 250);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.BackColor = System.Drawing.Color.White;

            // 标题
            var lblTitle = new Label();
            lblTitle.Text = "正在更新应用程序";
            lblTitle.Font = new System.Drawing.Font("微软雅黑", 12, System.Drawing.FontStyle.Bold);
            lblTitle.ForeColor = System.Drawing.Color.FromArgb(0, 122, 204);
            lblTitle.AutoSize = true;
            lblTitle.Location = new System.Drawing.Point(20, 20);

            // 进度条
            progressBar = new ProgressBar();
            progressBar.Size = new System.Drawing.Size(390, 23);
            progressBar.Location = new System.Drawing.Point(20, 70);
            progressBar.Style = ProgressBarStyle.Continuous;

            // 进度标签
            lblProgress = new Label();
            lblProgress.Text = "准备更新...";
            lblProgress.Font = new System.Drawing.Font("微软雅黑", 9);
            lblProgress.AutoSize = true;
            lblProgress.Location = new System.Drawing.Point(20, 100);

            // 状态标签
            lblStatus = new Label();
            lblStatus.Text = "状态: 等待开始";
            lblStatus.Font = new System.Drawing.Font("微软雅黑", 9);
            lblStatus.AutoSize = true;
            lblStatus.Location = new System.Drawing.Point(20, 130);

            // 取消按钮
            btnCancel = new Button();
            btnCancel.Text = "取消";
            btnCancel.Size = new System.Drawing.Size(80, 30);
            btnCancel.Location = new System.Drawing.Point(330, 160);
            btnCancel.Click += BtnCancel_Click;

            // 添加到窗体
            this.Controls.Add(lblTitle);
            this.Controls.Add(progressBar);
            this.Controls.Add(lblProgress);
            this.Controls.Add(lblStatus);
            this.Controls.Add(btnCancel);

            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private ProgressBar progressBar;
        private Label lblProgress;
        private Label lblStatus;
        private Button btnCancel;

        private void SetupBackgroundWorker()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
        }

        private void StartUpdate()
        {
            backgroundWorker.RunWorkerAsync();
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;

            try
            {
                // 步骤1: 下载更新包
                worker.ReportProgress(10, "正在下载更新包...");
                updateManager.DownloadProgressChanged += (progress, status) =>
                {
                    worker.ReportProgress(10 + (int)(progress * 0.6), status);
                };
                updateManager.DownloadUpdate();

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                // 步骤2: 创建备份
                worker.ReportProgress(70, "正在创建备份...");
                updateManager.BackupApplication();

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                // 步骤3: 应用更新
                worker.ReportProgress(80, "正在应用更新...");
                updateManager.ApplyUpdate();

                if (worker.CancellationPending)
                {
                    //e.CancellationPending = true;
                    e.Cancel = true;
                    return;
                }

                // 步骤4: 更新配置
                worker.ReportProgress(90, "正在更新配置...");
                updateManager.UpdateLocalVersion();

                worker.ReportProgress(100, "更新完成！");
                e.Result = true;
            }
            catch (Exception ex)
            {
                e.Result = ex;
            }
        }

        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
            lblProgress.Text = $"{e.ProgressPercentage}%";
            lblStatus.Text = $"状态: {e.UserState}";
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                lblStatus.Text = "状态: 更新已取消";
                MessageBox.Show("更新已被取消。", "取消", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (e.Error != null)
            {
                lblStatus.Text = "状态: 更新失败";
                progressBar.Value = 0;
                MessageBox.Show($"更新失败: {e.Error.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (e.Result is bool success && success)
            {
                UpdateSuccessful = true;
                lblStatus.Text = "状态: 更新成功";
                progressBar.Value = 100;

                // 自动关闭窗口
                System.Windows.Forms.Timer closeTimer = new System.Windows.Forms.Timer();
                closeTimer.Interval = 1500;
                closeTimer.Tick += (s, args) =>
                {
                    closeTimer.Stop();
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                };
                closeTimer.Start();
            }

            btnCancel.Enabled = false;
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
            {
                var result = MessageBox.Show("确定要取消更新吗？", "确认取消",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    backgroundWorker.CancelAsync();
                    btnCancel.Enabled = false;
                }
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (backgroundWorker.IsBusy && !backgroundWorker.CancellationPending)
            {
                e.Cancel = true;
                MessageBox.Show("请等待更新完成或取消更新。", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            base.OnFormClosing(e);
        }
    }
}